
package commonInfrastructure.system.filter;


import commonInfrastructure.accountManagement.entity.EmployeeEntity;
import commonInfrastructure.accountManagement.entity.FunctionalityEntity;
import commonInfrastructure.accountManagement.entity.RoleEntity;
import commonInfrastructure.accountManagement.session.EmployeeSessionBean;
import commonInfrastructure.accountManagement.session.FunctionalitySessionBean;
import java.io.IOException;
import java.lang.String;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName = "loginFilter", urlPatterns = {"*.xhtml"})
public class loginFilter implements Filter {
    
    private FilterConfig fc = null;
    @EJB 
    EmployeeSessionBean employeeManager;
    @EJB
    FunctionalitySessionBean functionalityManager;
    public loginFilter() {
    }    
    public void init(FilterConfig filterConfig) throws ServletException{
        fc = filterConfig;
    }
    public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain)throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //String pageRequested = req.getRequestURL().toString();
        
        String pagePath = req.getServletPath();
        if(req.getSession(true).getAttribute("isLogin") == null){
            req.getSession(true).setAttribute("isLogin",false);
        }
        Boolean isLogin = (Boolean)req.getSession(true).getAttribute("isLogin");
        if(!excludeLoginCheck(pagePath))
        {
            if(isLogin == true){
               Long employeeId = (Long)req.getSession().getAttribute("userId");
               if(checkAccessRight(employeeId, pagePath)) 
               chain.doFilter(request, response);
               //SystemUser systemUser = (SystemUser)session.getAttibute("systemUser");
               //chain.doFilter(request, response);
               else{
                   req.getRequestDispatcher("/commonInfrastructure/AccessDeniedPage.xhtml").forward(req,resp);
               }
        }
        else{
            req.getSession(true).setAttribute("lastAction", pagePath);    
            req.getRequestDispatcher("/commonInfrastructure/login.xhtml").forward(req,resp);  
        }
        }
        else
            chain.doFilter(request, response);
    }
    private Boolean excludeLoginCheck(String path)
    {
        if(path.contains("index.xhtml") ||
           path.contains("login.xhtml") ||           
           path.startsWith("/javax.faces.resource")||
           path.startsWith("/resources") ||    
           path.contains("accountManagement")||  
           path.contains("commonInfrastructure")|| 
           path.contains("salesOrderProcessing")||
           path.contains("companyManagement")||    
           path.contains("message")||
           path.contains("mrp")||
           path.contains("resetPassword")||    
                path.contains("scm")||
                path.contains("crm")||
           path.endsWith("/"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    
    private Boolean checkAccessRight(Long employeeId, String path)
    {
        if(path.equals("/test.xhtml") ||
           path.equals("/error.xhtml"))
        {
            return true;
        }
        else
        {
            EmployeeEntity employee = employeeManager.getEmployeeById(employeeId);
            String accessRight = path.replaceAll(".xhtml", "");
            accessRight = accessRight.substring(1);

//            int startIndex = accessRight.indexOf("/");
//
//            int endIndex = accessRight.substring(startIndex + 1).indexOf("/") + startIndex;
//
//            
//            startIndex ++;
//            endIndex ++;
//
//            String accessField = accessRight.substring(startIndex, endIndex);

//            String accessFunction = accessRight.substring(splitIndex,accessRight.length()); TODO: delete if not in use

            Boolean flag = false;
            List<RoleEntity> roleList = employee.getRoles();
            for(RoleEntity role: roleList){
                List<FunctionalityEntity> functionalityList = role.getFunctionalities();
                    for(FunctionalityEntity functionality : functionalityList){                   
                        if(accessRight.contains(functionality.getFuncName())){
                        flag = true;
                        break;
                    }
                }
            }
      return flag;
    }
    }

    public void destroy() {        
    }
}
